<template>
	<view class="container flex_C">
		<FeNavbar :isBorder="false">
			<view class="nav-slot-right" slot="right" @click="handleItemEvent({action:'navRightBtn'})">
				<view class="child-name van_ellipsis">{{selectChildAccount || "未选择"}}</view>
				<image :class="showSheet ? 'selecticon-top' : ''" src="@/static/order/select-icon.png"
					mode="aspectFill">
				</image>
			</view>
		</FeNavbar>
		<view class="scroll-wrap">
			<z-paging :fixed="false" :auto-show-system-loading="true" ref="pagingOne" v-model="orderData"
				@query="reqList" :refresher-enabled='false'>
				<view class="top-tabs">
					<view class="tab-item" :class="tabIndex == index ? 'tab-active' : ''" v-for="(item,index) in tabs"
						:key="index" @click="handleItemEvent({action:'tabsEvent',index})">
						{{item}}
						<view class="tab-underline" v-if="tabIndex == index"></view>
					</view>
				</view>
				<view class="account-info-wrap">
					<view class="status-row">
						<text>总资产</text>
						<text class="status-txt">
							{{accountDetail && accountDetail.status ? accountDetail.status : "--"}}
						</text>
					</view>
					<view class="money-row" @click="handleItemEvent({action:'changeUnit'})">
						<text class="money-value">
							{{accountConvert}}
						</text>
						<text class="money-unit">{{unit}}</text>
						<image src="/static/mine/jt-top.png" mode="aspectFill"></image>
					</view>
					<view class="money-balance">未使用资金
						{{accountDetail && accountDetail.unusedFunds ? accountDetail.unusedFunds : 0}}USDT
					</view>
					<view class="earnings-row">
						<view class="ea-item">
							<text>当前收益</text>
							<text class="ea-value">
								<template v-if="accountDetail && accountDetail.curProfit">
									{{accountDetail.curProfit >= 0 ? "+" : "-"}} {{accountDetail.curProfit}}
								</template>
								<template v-else>0</template>
								<text style="margin-left: 6rpx;">USDT</text>
							</text>
						</view>
						<view class="ea-item">
							<text>累计收益</text>
							<text class="ea-value">
								<template v-if="accountDetail && accountDetail.accProfit">
									{{accountDetail.accProfit >= 0 ? "+" : "-"}} {{accountDetail.accProfit}}
								</template>
								<template v-else>0</template>
								<text style="margin-left: 6rpx;">USDT</text>
							</text>
						</view>
					</view>
					<view class="menu-btns">
						<view class="btn btn1" @click="handleItemEvent({action:'buyIn'})">买入</view>
						<view class="btn btn2" @click="handleItemEvent({action:'allSell'})">一键平仓</view>
					</view>
					<view class="line-box"></view>
					<view class="account-box">
						<text class="row-title">子账号邮箱</text>
						<text class="account-box-value van_ellipsis">{{accountDetail.subAccountName||"--"}}</text>
						<!-- <template v-if="edit_child_account">
							<input class="edit-input" type="text" :value="accountDetail.subAccountName" maxlength="255"
								confirm-type="next" auto-focus placeholder="请输入子账号邮箱" data-action_key="child_account"
								style="background-color: #efefef;height:100%" @blur="handleEditInputBlur" />
						</template>
						<template v-else>
							<text class="account-box-value van_ellipsis" @click="edit_child_account = true">
								{{accountDetail && accountDetail.subAccountName ? accountDetail.subAccountName : "--"}}
							</text>
						</template> -->
					</view>
					<view class="account-box">
						<text class="row-title">api key</text>
						<text class="account-box-value van_ellipsis" @click="edit_api_key = true">
							{{accountDetail && accountDetail.apiKey ? accountDetail.apiKey : "--"}}
						</text>
					</view>
					<view class="account-box">
						<text class="row-title">secret key</text>
						<text class="account-box-value van_ellipsis" @click="edit_secret_key = true">
							{{accountDetail && accountDetail.secretKey ? accountDetail.secretKey : "--"}}
						</text>
					</view>
					<view class="account-box">
						<text class="row-title">IP地址</text>
						<text class="account-box-value van_ellipsis">
							{{accountDetail && accountDetail.ipWhite ? accountDetail.ipWhite : "0.0.0.0"}}
						</text>
						<view class="copy-ip" @click="handleItemEvent({action:'copyIp'})">复制</view>
					</view>
				</view>
				<view style="height: 24rpx;background-color: #F5F7F8;"></view>
				<view class="child-orders">
					<view class="head-change">
						<view class="head-content">
							<view class="order-switch" :class="subTabIndex == 0 ? 'tab-active' : ''"
								@click="handleItemEvent({action:'subTabsEvent',index:0})">当前订单</view>
							<view class="order-switch" :class="subTabIndex == 1 ? 'tab-active' : ''"
								@click="handleItemEvent({action:'subTabsEvent',index:1})">历史订单</view>
						</view>
					</view>
				</view>
				<view style="background-color: #fff;padding: 32rpx 0 0 0;">
					<orderItem :datas="orderData" :scene="subTabIndex == 0 ? 'childNow' : 'childHistory'" />
				</view>
			</z-paging>
		</view>
		<!-- 子账号选择 -->
		<u-picker :closeOnClickOverlay="true" :show="pickerShow" :defaultIndex="defaultIndex" keyName="subAccountName"
			:columns="childList" confirmColor="#FFE269" @cancel="pickerShow = false" @confirm="handlePickerConfirm">
		</u-picker>

		<!-- 一键平仓 -->
		<onKeyClearPanel ref="refOnKeyClearPanel" @complete="handleClearComplete" />
	</view>
</template>

<script>
	import childAccountDetailItem from "./components/childAccountDetailItem.vue"
	import orderItem from "../../order/components/orderItem.vue"
	import {
		updateApi,
		listApi,
		accountInfo
	} from '@/api/subAccount.js'
	import {
		childOrderNow,
		childOrderHistory
	} from "@/api/order.js"
	import {
		validateEmail
	} from "@/util/helper.js"

	export default {
		components: {
			childAccountDetailItem,
			orderItem
		},
		data() {
			return {
				showSheet: false,
				tabs: ["总览", "现货", "资金", "合约"],
				key: ["total", "spot", "funding", "futures"],
				tabIndex: 0,
				subTabIndex: 0,

				pickerShow: false,
				defaultIndex: [0],
				selectChildAccount: "", // 选择的子账号
				childList: [
					[]
				],
				subAccountId: null, // 当前选择的子账号id
				option: null,
				orderData: [],
				accountDetail: {},
				amount: 0,
				accountConvert: 0,
				unit: 'USDT',
				rate: 1,

				edit_child_account: false,
				edit_api_key: false,
				edit_secret_key: false,
			};
		},
		async onLoad(option) {
			const rates = uni.getStorageSync('rates')
			this.rate = rates[0].rate
			const {
				id,
				index
			} = option;
			// const subAccountList = uni.getStorageSync('subAccountList');
			// this.childList = [subAccountList]
			// this.defaultIndex = [
			// 	[index]
			// ]
			// this.selectChildAccount = subAccountList[index].subAccountName
			this.option = option
			this.subAccountId = id;
			await this.getList();
			this.reqAccountInfo()
		},
		watch: {
			unit: {
				handler(newVal) {
					this.accountConvert = newVal == 'USDT' ? this.amount : (this.amount * this.rate).toFixed(2)
				}
			},
			amount: {
				handler(newVal) {
					this.accountConvert = this.unit == 'USDT' ? newVal : (newVal * this.rate).toFixed(2)
				}
			}
		},
		methods: {
			async getList() {
				const res = await listApi();
				const datas = res.data.subAccounts;
				this.childList = [datas];

				for (let a = 0; a < datas.length; a++) {
					if (datas[a].subAccountId == this.option.id) {
						this.subAccountId = datas[a].subAccountId;
						this.defaultIndex = [a];
						this.selectChildAccount = datas[a].subAccountName;
						break;
					}
				}
			},
			reqAccountInfo() {
				uni.showLoading({
					title: '加载中~',
					mask: true
				})
				accountInfo(this.subAccountId).then(res => {
					this.accountDetail = res.data;
					this.amount = res.data.balances[this.key[this.tabIndex]]
				}).finally(() => {
					uni.hideLoading()
				});
			},
			handleItemEvent(vals) {
				const {
					action,
					index
				} = vals;
				switch (action) {
					case "navRightBtn":
						if (JSON.stringify(this.childList) == "[[]]") {
							uni.showToast({
								title: "当前账号无子账号",
								icon: "none"
							})
							return
						}
						this.pickerShow = true;
						break;
					case "tabsEvent": // tab事件
						this.tabIndex = index;
						this.amount = this.accountDetail.balances[this.key[index]]
						break;
					case "subTabsEvent":
						this.subTabIndex = index;
						this.$refs.pagingOne.reload();
						break;
					case "allSell":
						this.$refs.refOnKeyClearPanel.show({
							level: "sub_account",
							subAccountId: Number(this.subAccountId)
						});
						break;
					case "copyIp": // 复制IP
						uni.setClipboardData({
							data: this.accountDetail.ipWhite,
							success() {
								uni.showToast({
									title: '复制成功~',
									icon: 'success'
								})
							}
						})
						break;
					case "changeUnit": // 切换单位
						uni.showActionSheet({
							itemList: ["CNY", "USDT"],
							success: (res) => {
								this.unit = res.tapIndex ? 'USDT' : 'CNY';
							}
						})
						break;

					case "buyIn": // 买入
						uni.setStorageSync('currentSubAccountId', this.subAccountId)
						uni.switchTab({
							url: '/pages/tabbar/trading/trading'
						})
						break;
				}
			},

			handlePickerConfirm(vals) {
				this.selectChildAccount = vals.value[0].subAccountName;
				this.subAccountId = vals.value[0].subAccountId;
				this.pickerShow = false;
				this.reqAccountInfo()
				this.$refs.pagingOne.reload();
			},
			reqList(pageNo, pageSize) {
				// 可能得极端情况：组件[z-paging]加载了，onload还未触发，导致subAccountId为空。非必现，某些机型会有
				if (this.isEmpty(this.subAccountId)) {
					this.subAccountId = this.option.id
				}
				if (this.subTabIndex == 0) {
					childOrderNow({
						limit: pageSize,
						page: pageNo,
						subAccountId: this.subAccountId
					}).then(res => {
						this.$refs.pagingOne.complete(res.data.orders);
					}).catch(res => {
						this.$refs.pagingOne.complete(false);
					})

				} else {
					childOrderHistory({
						limit: pageSize,
						page: pageNo,
						subAccountId: this.subAccountId
					}).then(res => {
						this.$refs.pagingOne.complete(res.data.orders);
					}).catch(res => {
						this.$refs.pagingOne.complete(false);
					})
				}
			},
			handleClearComplete() {
				if (this.subTabIndex) return
				this.$refs.pagingOne.reload();
			},

			// 子账号信息编辑输入框，失去焦点
			async handleEditInputBlur(vals) {
				const {
					action_key
				} = vals.currentTarget.dataset;
				const newValue = vals.detail.value;

				// 编辑子账号邮箱
				if (action_key == "child_account") {
					if (this.isEmpty(newValue)) {
						uni.showToast({
							title: '邮箱不能为空',
							icon: 'none'
						})
						return
					}

					if (!validateEmail(newValue)) {
						uni.showToast({
							title: '输入邮箱有误',
							icon: 'none'
						})
						return
					}

					this.edit_child_account = false;

					if (this.accountDetail.subAccountName != newValue) {
						uni.showLoading({
							title: '编辑中...'
						})
						await updateApi(this.subAccountId, {
							subAccountName: newValue
						});
						uni.showToast({
							title: '编辑成功',
						})
						this.reqAccountInfo();
					}

					return
				}

				// 编辑 api_key
				if (action_key == "api_key") {

					if (this.isEmpty(newValue)) {
						uni.showToast({
							title: 'apiKey不能为空',
							icon: 'none'
						})
						return
					}

					this.edit_api_key = false;

					if (this.accountDetail.apiKey != newValue) {
						uni.showLoading({
							title: '编辑中...'
						})
						await updateApi(this.subAccountId, {
							apiKey: newValue
						});
						uni.showToast({
							title: '编辑成功',
						})
						this.reqAccountInfo();
					}

					return
				}

				// 编辑secret_key
				if (action_key == "secret_key") {

					if (this.isEmpty(newValue)) {
						uni.showToast({
							title: 'secretKey不能为空',
							icon: 'none'
						})
						return
					}

					this.edit_secret_key = false;

					if (this.accountDetail.secretKey != newValue) {
						uni.showLoading({
							title: '编辑中...'
						})
						await updateApi(this.subAccountId, {
							secretKey: newValue
						});
						uni.showToast({
							title: '编辑成功',
						})
						this.reqAccountInfo();
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/ .u-popup {
		position: fixed;
		z-index: 999;
	}

	/deep/ .u-popup__content {
		border-radius: 20rpx 20rpx 0 0;
	}

	.container {
		height: 100vh;
		overflow: hidden;
		background-color: #ffffff;

		.nav-slot-right {
			padding: 20rpx 0;
			display: flex;
			align-items: center;

			.child-name {
				font-size: 28rpx;
				color: $font-color;
				line-height: 33rpx;
				max-width: 400rpx;
			}

			image {
				width: 24rpx;
				height: 24rpx;
				margin-left: 10rpx;
				transition: 0.2s ease;
			}

			.selecticon-top {
				transform: rotate(180deg);
			}
		}

		.top-tabs {
			height: 80rpx;
			line-height: 80rpx;
			border-bottom: 1px solid #DBE0E6;
			display: flex;
			align-items: center;
			background-color: #fff;

			.tab-item {
				height: 100%;
				font-size: 28rpx;
				color: #7B828A;
				padding: 0 22rpx;
				position: relative;
			}

			.tab-active {
				color: $font-color;
				font-size: 30rpx;
				font-weight: 600;
			}

			.tab-underline {
				width: 46rpx;
				height: 8rpx;
				background-color: #26282B;
				border-radius: 20rpx 20rpx 0 0;
				position: absolute;
				bottom: 0rpx;
				left: 28rpx;
			}
		}

		.scroll-wrap {
			flex: 1;
			height: 0;
			position: relative;
			z-index: 1;
		}

		.account-info-wrap {
			padding: 40rpx 32rpx 32rpx 32rpx;
			background-color: #ffffff;

			.status-row {
				display: flex;
				align-items: center;
				justify-content: space-between;

				text {
					font-size: 26rpx;
					color: #7B828A;
					line-height: 30rpx;
				}

				.status-txt {
					background-color: rgba(6, 176, 112, 0.10);
					padding: 6rpx 20rpx;
					font-size: 22rpx;
					color: #06B070;
					line-height: 26rpx;
				}
			}

			.money-row {
				color: #26282B;
				font-weight: bold;
				display: inline-block;
				line-height: 70rpx;
				margin-top: 20rpx;

				.money-value {
					font-size: 64rpx;
					line-height: 75rpx;
				}

				.money-unit {
					line-height: 45rpx;
					font-size: 38rpx;
					margin: 0 12rpx;
				}

				image {
					width: 24rpx;
					height: 24rpx;
				}
			}

			.money-balance {
				font-size: 26rpx;
				line-height: 30rpx;
				color: #A6ACB4;
				padding: 12rpx 0 32rpx 0;
			}

			.earnings-row {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.ea-item {
					text {
						font-size: 26rpx;
						line-height: 30rpx;
						color: #7B828A;
					}

					.ea-value {
						color: #06B070;
						margin-left: 12rpx;
					}
				}
			}

			.menu-btns {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-top: 40rpx;
				;

				.btn {
					flex: 1;
					height: 88rpx;
					line-height: 88rpx;
					text-align: center;
					border-radius: 12rpx;
					font-weight: 600;
				}

				.btn1 {
					color: #ffffff;
					background-color: #63D0A8;
					margin-right: 42rpx;
				}

				.btn2 {
					color: $font-color;
					background-color: $btn-bg-color;
				}
			}

			.line-box {
				height: 1px;
				border-bottom: 1px dashed #A6ACB4;
				margin-bottom: 30rpx;
				margin-top: 40rpx;
			}

			.account-box {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-radius: 12rpx;
				border: 1px solid #DBE0E6;
				margin-bottom: 20rpx;
				padding: 0 20rpx;

				.row-title {
					width: 200rpx;
					font-size: 26rpx;
					color: #7B828A;
				}

				.account-box-value {
					flex: 1;
					color: $font-color;
					font-size: 28rpx;
					text-align: right;
					margin-left: 40rpx;
				}

				.copy-ip {
					width: 92rpx;
					height: 46rpx;
					line-height: 46rpx;
					text-align: center;
					background-color: #EEF1F6;
					color: #7B828A;
					font-size: 22rpx;
					border-radius: 8rpx;
					margin-left: 12rpx;
				}

				.edit-input {
					text-align: right;
				}
			}
		}

		.child-orders {
			position: sticky;
			background-color: #fff;
			padding: 0 32rpx;
			padding-bottom: 10rpx;

			.head-change {
				display: flex;
				align-items: center;
				justify-content: center;

				.head-content {
					display: flex;
					align-items: center;
					justify-content: center;
					background-color: #F5F7F8;
					border-radius: 12rpx;
					margin-top: 24rpx;
					padding: 8rpx;
				}

				.order-switch {
					width: 144rpx;
					height: 56rpx;
					line-height: 56rpx;
					text-align: center;
					font-size: 26rpx;
					color: #7B828A;
				}

				.tab-active {
					color: $font-color;
					background-color: #fff;
					border-radius: 12rpx;
				}
			}
		}
	}
</style>